import { _decorator, Component, Node, Prefab, instantiate, input, Input, RigidBody ,Vec3} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('createBullet')
export class createBullet extends Component {
    @property({ type: Prefab })
    public bullet = null
    @property({ type: Node })
    public camera = null
    @property({ type: Number })
    public fireTime = 0.2
    @property({ type: Number })
    public bulletSpeed = 40
    // @property({ type: Node })
    // public bulletGroup = null;

    private timer: number = 0;
    private fireSwitch: boolean = false;

    start() {
        input.on(Input.EventType.TOUCH_START, this.touchStart, this)
        input.on(Input.EventType.TOUCH_END, this.touchEnd, this)
    }

    update(deltaTime: number) {
        if (this.fireSwitch) {
            this.timer += deltaTime;
            if (this.timer > this.fireTime) {
                this.createBullet()
                this.timer = 0
            }
        }
    }
    touchStart() {
        this.fireSwitch = true;
    }

    touchEnd() {
        this.fireSwitch = false;
    }

    createBullet() {
        const obj = instantiate(this.bullet);
        obj.setParent(this.node);
        obj.setPosition(this.camera.position.x, this.camera.position.y - 1, this.camera.position.z);
        let rigidbody:RigidBody = obj.getComponent(RigidBody);
        rigidbody.setLinearVelocity(new Vec3(0,0,-this.bulletSpeed));

    }
    destroyAllChildren(){
        this.node.destroyAllChildren()
    }
}


